#include <iostream>
#include <event2/buffer.h>
#include "event_handler.h"
#include "http_request_dispatcher.h"
#include "http_controller.h"
#include "scanner_processor.h"
#include "constants.h"

static const std::string REGISTED_URLS[] = { "/iaplugin/scanner" };
static HttpController* REGISTED_CONTROLLERS[] = { static_cast<HttpController*>(&SCANNER_PROCESSOR) };

std::map<const std::string, HttpController&> HttpRequestDispatcher::m_pControllerMap;
HttpRequestDispatcher HttpRequestDispatcher::m_pInstance;

HttpRequestDispatcher::HttpRequestDispatcher() {
    InitControllerMapping();
}

void HttpRequestDispatcher::InitControllerMapping()
{
    int i = 0;
    for (auto elem : REGISTED_URLS)
    {
        m_pControllerMap.insert(std::pair<const std::string, HttpController&>(elem, *REGISTED_CONTROLLERS[i]));
        ++i;
    }
}

void HttpRequestDispatcher::RegisterControllerMapping(const std::string url, HttpController& controller, bool override )
{
    //todo: no handle the existed url
    if (static_cast<HttpController*>(&(HandleRequestMapping(url))) && override)
    {
        std::cout << "the url has been registered.." << std::endl;
        return;
    }
    m_pControllerMap.insert(std::pair<std::string, HttpController&>(url, controller));
}

HttpRequestDispatcher& HttpRequestDispatcher::GetInstace()
{
    return m_pInstance;
}

HttpController& HttpRequestDispatcher::HandleRequestMapping(const std::string url)
{
    //check return value not null
    auto iter = m_pControllerMap.find(url);
    if (iter == m_pControllerMap.end())
    {
        std::cout << "coundnot find the controller for :" << url << std::endl;
        return *static_cast<HttpController *>(nullptr);
    }
    return iter->second;
}
